package com.ikingtech.platform.business.message.service.router;

import com.ikingtech.framework.sdk.enums.message.MessageSendChannelEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.push.common.*;
import lombok.RequiredArgsConstructor;

import java.util.Map;

import static com.ikingtech.framework.sdk.utils.Tools.Str.CONTENT_PLACEHOLDER_PREFIX;
import static com.ikingtech.framework.sdk.utils.Tools.Str.CONTENT_PLACEHOLDER_SUFFIX;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class SystemMessageRouter implements MessageRouter{

    @Override
    public RouteResult route(RouteRequest request) {
        PushRequest pushRequest = this.parseBody(request);
        DeliverResult result = PushManager.websocket().send(pushRequest, request.getTarget().getId());
        return new RouteResult(pushRequest.getBody().getText(), Tools.Coll.convertList(pushRequest.getBody().getRedirectTo(), MessageRedirect::getRedirectLink), result.getSuccess(), result.getCause());
    }

    /**
     * 格式化消息内容
     *
     * @param request 消息参数
     * @return 格式化后的消息
     */
    private PushRequest parseBody(RouteRequest request) {
        PushRequest pushRequest = new PushRequest();
        MessageBody body = new MessageBody();
        Map<String, Object> messageParamMap = Tools.Json.objToMap(request.getMessageWrapper());
        if (Tools.Coll.isBlankMap(messageParamMap) ||
                !request.getTemplateContent().contains(CONTENT_PLACEHOLDER_PREFIX)) {
            body.setText(request.getTemplateContent());
        } else {
            body.setText(Tools.Str.replace(request.getTemplateContent(), CONTENT_PLACEHOLDER_PREFIX, CONTENT_PLACEHOLDER_SUFFIX, messageParamMap));
        }
        Boolean ignoreRedirect = (Boolean) messageParamMap.get("ignoreRedirect");
        if (!Boolean.TRUE.equals(ignoreRedirect)) {
            body.setRedirectTo(this.createMessageRedirect(request.getRedirectDefinitinoMap(), messageParamMap));
        }
        body.setBusinessKey(request.getBusinessKey());
        body.setShowNotification(request.getShowNotification());
        pushRequest.setBody(body);
        return pushRequest;
    }

    @Override
    public MessageSendChannelEnum channel() {
        return MessageSendChannelEnum.SYSTEM;
    }
}
